﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;

using UploadManager;
//using StoreClientModule;
using UnityCore;

namespace MBB_Store_Sales_Report
{
    public partial class frmChargeInvoiceViewer : Form
    {
        DataTable exportChargeInvoice = new DataTable();
        DataTable exportChargeInvoiceItem = new DataTable();
        DataTable exportChargePayments = new DataTable();
        DataTable exportChargeBalance = new DataTable();
        DataTable exportInvoice = new DataTable();

        double totalInvoiceAmount = 0.0;
        double totalPayment = 0.0;
        double balance = 0.0;

        SynchronizeData sync = new SynchronizeData();
        Threader t = new Threader();
        readDetails path = new readDetails();
        readDetails auto = new readDetails();
        autoDetails aSoldTo = new autoDetails();

        struct invoiceDetails
        {
            public string accountName;
            public string invoiceDate;
        }

        int pp = 1;
        int cnt = 0;

        public frmChargeInvoiceViewer()
        {
            InitializeComponent();
       
            btnView.Click += new EventHandler(btnView_Click);
            btnClose.Click += new EventHandler(btnClose_Click);
            panel2.EnabledChanged += new EventHandler(panel2_EnabledChanged);

            sync.ProcessCompleted += new UnityCore.CoreHandler(sync_ProcessCompleted);
            sync.ProcessError += new UnityCore.CoreHandler(sync_ProcessError);
            txtAcctName.KeyPress +=new KeyPressEventHandler(txtAcctName_KeyPress);
            btnPrint.Click += new EventHandler(btnPrint_Click);
            cmbStore.SelectedIndexChanged +=new EventHandler(cmbStore_SelectedIndexChanged);
        }
        
        void txtAcctName_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (txtAcctName.Text != "")
                {
                    if (e.KeyChar != (char)27 && e.KeyChar != (char)13)
                    {
                        if (txtAcctName.Items.Count > 0) txtAcctName.DroppedDown = true; else txtAcctName.DroppedDown = false;
                        aSoldTo.search = txtAcctName.Text;
                        aSoldTo.tbl = exportInvoice;
                        sync.AutoInvoice(aSoldTo);
                    }
                    else
                    {
                        txtAcctName.DroppedDown = false;
                    }
                }

            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }

        void cmbStore_SelectedIndexChanged(object sender, EventArgs e)
        {
            auto.date = "";
            auto.remNode = cmbStore.Text;
            auto.fileName = "Charge Invoice";
            sync.Auto(auto);
        }
        void sync_ProcessError(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(msg);
            });
        }

        void sync_ProcessCompleted(string pcode, string msg)
        {
            t.SafeCall(this, delegate
            {
                switch (pcode)
                {
                    case "GetStores":
                        cmbStore.Items.AddRange(sync.stores);
                        break;
                    case "AutoInvoice":
                        if (sync.ListAutoInvoice.Length > 0)
                        {
                            txtAcctName.Items.Clear();
                            txtAcctName.Items.AddRange(sync.ListAutoInvoice);
                            txtAcctName.SelectionStart = txtAcctName.Text.Length;
                        }
                        break;
                    case "Auto":
                        exportInvoice = sync.export.DefaultView.ToTable(true, new string[] { "fInvoice" });
                        break;
                    case "ReadMany":
                        exportChargeInvoice = sync.exportTables[0];
                        exportChargeInvoiceItem = sync.exportTables[1];
                        exportChargePayments = sync.exportTables[2];
                        exportChargeBalance = sync.exportTables[3];

                        grd.DataSource = extractInvoiceItems();
                        grd.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        grd.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        txtTotal.Text = Common.FormatCurrency(totalInvoiceAmount);

                        extractBalance();

                        grd2.DataSource = extractPayments();
                        grd2.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        txtTotalPayment.Text = Common.FormatCurrency(totalPayment);
                        ControlState(true);
                        break;
                }

            });
        }
        
        DataTable extractInvoiceItems()
        {
            invoiceDetails iD = new invoiceDetails();

            for (int i = 0; i < exportChargeInvoice.Rows.Count; i++)
            {
                if (txtAcctName.Text.Equals(exportChargeInvoice.Rows[i]["fInvoice"].ToString()))
                {
                    iD.invoiceDate = exportChargeInvoice.Rows[i]["fDate"].ToString();
                    iD.accountName = exportChargeInvoice.Rows[i]["fSoldTo"].ToString();
                    break;
                }
            }
            txtDate.Text = iD.invoiceDate;
            label5.Text = iD.accountName;

            DataTable dt = new DataTable();
            totalInvoiceAmount = 0.0;
            dt.Columns.Clear();
            dt.Rows.Clear();

            dt.Columns.Add("Qty");
            dt.Columns.Add("Unit");
            dt.Columns.Add("Description");
            dt.Columns.Add("Unit Price");
            dt.Columns.Add("Amount");

            for (int i = 0; i < exportChargeInvoiceItem.Rows.Count; i++)
            {
                if (txtAcctName.Text.Equals(exportChargeInvoiceItem.Rows[i]["fInvoice"].ToString()))
                {
                    DataRow dr = dt.NewRow();
                    dr["Qty"] = exportChargeInvoiceItem.Rows[i]["fQty"].ToString();
                    dr["Unit"] = exportChargeInvoiceItem.Rows[i]["fUnit"].ToString();
                    dr["Description"] = exportChargeInvoiceItem.Rows[i]["fDescription"].ToString();
                    dr["Unit Price"] = exportChargeInvoiceItem.Rows[i]["fUnitPrice"].ToString();

                    double amt = double.Parse(exportChargeInvoiceItem.Rows[i]["fQty"].ToString()) * double.Parse(exportChargeInvoiceItem.Rows[i]["fUnitPrice"].ToString());
                    dr["Amount"] = Common.FormatCurrency(amt);
                    totalInvoiceAmount += amt;
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }

        void extractBalance()
        {
            balance = 0.0;
            for (int i = 0; i < exportChargeBalance.Rows.Count; i++)
            {
                if (txtAcctName.Text.Equals(exportChargeBalance.Rows[i]["fInvoice"].ToString()) && exportChargeBalance.Rows[i]["fStatus"].ToString().Equals("1"))
                {
                    balance = double.Parse(exportChargeBalance.Rows[i]["fBalance"].ToString());
                    break;
                }
            }
            txtBal.Text = Common.FormatCurrency(balance);
        }
        DataTable extractPayments()
        {
            totalPayment = 0.0;
            DataTable tp = new DataTable();
            tp.Columns.Clear();
            tp.Rows.Clear();

            tp.Columns.Add("Date");
            tp.Columns.Add("Account Name");
            tp.Columns.Add("OR Number");
            tp.Columns.Add("Check Number");
            tp.Columns.Add("Amount");

            for (int i = 0; i < exportChargePayments.Rows.Count; i++)
            {
                if (txtAcctName.Text.Equals(exportChargePayments.Rows[i]["fInvoiceNumber"].ToString()))
                {
                    DataRow dr = tp.NewRow();
                    dr["Date"] = exportChargePayments.Rows[i]["fDateReceived"].ToString();
                    dr["Account Name"] = exportChargePayments.Rows[i]["fAccountName"].ToString();
                    dr["OR Number"] = exportChargePayments.Rows[i]["fORNumber"].ToString();
                    dr["Check Number"] = exportChargePayments.Rows[i]["fCheckNumber"].ToString();
                    dr["Amount"] = exportChargePayments.Rows[i]["fAmount"].ToString();
                    double amt = double.Parse(exportChargePayments.Rows[i]["fAmount"].ToString());
                    tp.Rows.Add(dr);

                    totalPayment += amt;
                }
            }
            return tp;
        }

        void btnPrint_Click(object sender, EventArgs e)
        {
            if (grd.Rows.Count > 0)
            {
                PrintDocument pd = new PrintDocument();
                pd.DocumentName = lblText.Text;
                pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
                PrintDialog pdlg = new PrintDialog();
                pdlg.Document = pd;
                if (pdlg.ShowDialog() == DialogResult.OK)
                {
                    PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                    ppdlg.Document = pd;
                    //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                    ppdlg.ShowDialog();
                }
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0, lpp2= 0;
            float y = 0, y2=0, tmp = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left - 50;
            float rm = e.PageBounds.Width - 50;
            float bm = e.PageBounds.Height - 50;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();
            
            //Header
            y = 50;
            y2 = 150;

            cFont = new Font("Courier New", 14f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            y += ht;
            e.Graphics.DrawString(cmbStore.Text, cFont, Brushes.Black, e.PageBounds.Width / 2, y, sf);
            y += ht;
            e.Graphics.DrawString(Common.lStoreAddress, cFont, Brushes.Black, e.PageBounds.Width / 2, y, sf);
            y += ht;
            cFont = new Font("Courier New", 14f, FontStyle.Underline);
            e.Graphics.DrawString("CHARGE INVOICE NO: "+txtAcctName.Text, cFont, Brushes.Black, e.PageBounds.Width / 2, y, sf);

            y += ht + 30;
            cFont = new Font("Courier New", 12f, FontStyle.Underline);
            sf.Alignment = StringAlignment.Near;
            string str = label5.Text;
            e.Graphics.DrawString("Account Name: "+str, cFont, Brushes.Black, lm, y, sf);
            
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("Date: "+txtDate.Text, cFont, Brushes.Black, rm, y, sf);
            
            //Column Header
            y += ht + 15;
            cFont = new Font("Courier New", 12f, FontStyle.Regular);
            e.Graphics.FillRectangle(Brushes.LightGray, lm, y, rm - lm, ht);
            e.Graphics.DrawRectangle(new Pen(Brushes.Black), lm, y, rm - lm, ht);
            
            
            sf.Alignment = StringAlignment.Center;
            float cx = lm + (((rm - lm) * 10) / 100);
            float tx = lm + (((rm - lm) * 5f) / 100);
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Qty", cFont, Brushes.Black, tx, y, sf);
            
            cx += ((rm - lm) * 10) / 100;
            tx = cx - ((rm - lm) * 10) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Unit", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 40) / 100;
            tx = cx - ((rm - lm) * 40) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Description", cFont, Brushes.Black, tx, y, sf);

            cx += ((rm - lm) * 20) / 100;
            tx = cx - ((rm - lm) * 20) / 200;
            e.Graphics.DrawLine(new Pen(Brushes.Black), cx, y, cx, y + ht);
            e.Graphics.DrawString("Unit Price", cFont, Brushes.Black, tx, y, sf);

            tx += ((rm - lm) * 20) / 100;
            e.Graphics.DrawString("Amount", cFont, Brushes.Black, tx, y, sf);
            
            //Data
            y += ht * (1.5f);
            
            lpp = (bm - y) / ht;
            int cl = 0;
            float stx = 0, stx2 = 0; 
            
            while (cl <= lpp && cnt < grd.Rows.Count)
            {
                sf.Alignment = StringAlignment.Near;
                stx = lm + 2;
                
                str = grd.Rows[cnt].Cells["Qty"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                
                stx += ((rm - lm) * 10) / 100;
                str = grd.Rows[cnt].Cells["Unit"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 10) / 100;
                str = grd.Rows[cnt].Cells["Description"].Value.ToString();
                if (str.Length > 30)
                {
                    str = str.Substring(0, 25) + "...";
                }
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                sf.Alignment = StringAlignment.Far;
                stx += ((rm - lm) * 60) / 100;
                str = grd.Rows[cnt].Cells["Unit Price"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 20) / 100;
                str = grd.Rows[cnt].Cells["Amount"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);
                
                cnt++;
                cl++;
                y += ht;
            }

            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Total", cFont, Brushes.Blue, (lm + 2)+((rm - lm) * 60) / 100, y, sf);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString(""+txtTotal.Text, cFont, Brushes.Blue, (lm + 2)+((rm - lm) * 100) / 100, y, sf);
            
            
            
            //payment records
            y += ht * (1.5f);
            int cl2 = 0;
            lpp2 = (bm - y) / ht;
            int cnt2 = 0;
            

            while (cl2 <= lpp2 && cnt2 < grd2.Rows.Count)
            {
                sf.Alignment = StringAlignment.Near;
                stx = lm + 2;

                str = grd2.Rows[cnt2].Cells["Date"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 15) / 100;
                str = grd2.Rows[cnt2].Cells["OR Number"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                stx += ((rm - lm) * 20) / 100;
                str = grd2.Rows[cnt2].Cells["Check Number"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                sf.Alignment = StringAlignment.Far;
                stx += ((rm - lm) * 65) / 100;
                str = grd2.Rows[cnt2].Cells["Amount"].Value.ToString();
                e.Graphics.DrawString(str, cFont, Brushes.Black, stx, y, sf);

                cnt2++;
                cl2++;
                y += ht;
            }

            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Total", cFont, Brushes.Blue, (lm + 2) + ((rm - lm) * 60) / 100, y, sf);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("" + txtTotalPayment.Text, cFont, Brushes.Blue, (lm + 2) + ((rm - lm) * 100) / 100, y, sf);

            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Balance", cFont, Brushes.Blue, (lm + 2) + ((rm - lm) * 60) / 100, y+ht, sf);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("" + txtBal.Text , cFont, Brushes.Blue, (lm + 2) + ((rm - lm) * 100) / 100, y+ht, sf);
            if (cnt < grd.Rows.Count || cnt2 < grd2.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                e.HasMorePages = false;
                cnt = 0;
                cnt2 = 0;
                pp = 1;
            }
        }

        void btnView_Click(object sender, EventArgs e)
        {
            if (txtAcctName.Text != "" && cmbStore.Text != "")
            {
                ControlState(false);
                path.date = "";
                path.remNode = cmbStore.Text;
                path.fileNames.Clear();
                path.fileNames.Add("Charge Invoice");
                path.fileNames.Add("Charge Invoice Item");
                path.fileNames.Add("Charge Payments");
                path.fileNames.Add("Charge Balance");
                sync.ReadMany(path);
                
            }
        }
        void ControlState(bool state)
        {
            btnView.Enabled = state;
            btnPrint.Enabled = state;
            pnlMsg.Visible = !state;
        }
        void computeTotal()
        {
            double tAmount = 0.0f, tAmount2 = 0.0f;
            for (int i = 0; i < grd.Rows.Count; i++)
            {
                double amt = 0.0f;
                double.TryParse(grd.Rows[i].Cells[4].Value.ToString(), out amt);
                tAmount = tAmount + amt;
            }
            for (int i = 0; i < grd2.Rows.Count; i++)
            {
                double amt2 = 0.0f;
                double.TryParse(grd2.Rows[i].Cells[4].Value.ToString(), out amt2);
                tAmount2 = tAmount2 + amt2;
            }
            
            txtTotal.Text = Common.FormatCurrency(tAmount);
            txtTotalPayment.Text = Common.FormatCurrency(tAmount2);

        }

        void panel2_EnabledChanged(object sender, EventArgs e)
        {
            if (!panel2.Enabled)
            {
                panel2.BackColor = Color.MidnightBlue;
            }
            else
            {
                panel2.BackColor = Color.RoyalBlue;
            }
        }
        void btnClose_Click(object sender, EventArgs e)
        {
            pnlExpensesListOnline.Dispose();
            this.Dispose();
        }
        public Panel PanelForm
        {
            get { return pnlExpensesListOnline; }
        }
        public void Initialize(string Title)
        {
            this.Select();
            lblText.Text = Title;
            sync.Stores();
            path.fileNames = new List<string>();
        }
    }
}
